var express = require('express');
var router = express.Router();


var db = require('../model/index')

/* GET users listing. */
router.get('/', (req, res, next) => {
  let page = (req.query.page - 1)*10
  let page_max = req.query.page * 10
  let mysql = `SELECT * FROM books ORDER BY book_name DESC LIMIT ?,?`
  db(mysql,[page,page_max],(err,data)=> {
    
    if (err) {
      return res.json({
        state:500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message:'数据库操作成功',
      data:data
    })
  })
});

/* 获取页码. */
router.get('/pagetotal', (req, res, next) => {
  
  let mysql = `SELECT * FROM books;`
  db(mysql,[],(err,data)=> {
    if (err) {
      return res.json({
        state:500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message:'数据库操作成功',
      data:data
    })
  })
});

/* 增 */
router.post('/add', (req, res, next) => {
  let book_name = req.query.book_name;
  let book_price = req.query.book_price;
  let book_inventory = req.query.book_inventory;
  let book_intro = req.query.book_intro;
  let book_address = req.query.book_address;
  let book_data = req.query.book_data;
  let book_press = req.query.book_press;
  let mysql = `INSERT INTO books (book_name,book_price,book_borrow_num,book_inventory,book_img,book_intro,book_address,book_data,book_press) VALUES(?,?,'0',?,'2.jpg',?,?,?,?)`
  db(mysql,[book_name,book_price,book_inventory,book_inventory,book_intro,book_address,book_data,book_press],(err,data)=> {
    
    if (err) {
      return res.json({
        state:500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message:'添加操作成功'
    })
  })
});


/* GET users listing. */
router.delete('/delete', (req, res, next) => {
  let mysql = `DELETE FROM books WHERE book_id=?`
  db(mysql,[req.query.book_id],(err,data)=> {
    if (err) {
      return res.json({
        state:500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message:'数据库删除成功',
    })
  })
});

module.exports = router;